﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
using System.Text;

namespace KFGame
{
    public class KFSocketClient
    {
        //
        private byte[] result = new byte[1024];

        private Socket clientSocket;

        private string ip;

        private int port;

        Thread Recievethread;

        public string clientid;



        //断线重连
        public bool OfflineReconnection = true;

        //启动 或关闭
        public bool enter = true;


        public delegate void KFAction(string msg);

        public KFAction OnAction;

        public delegate void ConnenctFail();
        public ConnenctFail onFail;



        private static KFSocketClient client;

        public static KFSocketClient instantiation
        {
            get
            {
                if (client == null)
                    client = new KFSocketClient();

                return client;
            }
        }

        public KFSocketClient()
        {
        }

        public void Close()
        {
            enter = false;
            try
            {
                if (!IsConnected()) return;

                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
            catch
            {
                Debug.Log("连接关闭失败");
                return;
            }
        }

        /// <summary>
        /// 重连
        /// /// </summary>
        public void reconnent()
        {
            if (enter)
                ConnectServer(ip, port);
        }

        public bool IsConnected()
        {
            return (clientSocket != null && clientSocket.Connected);
        }

        /// <summary>
        /// 连接指定IP和端口的服务器
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public bool ConnectServer(string ipaddress, int portp)
        {
            ip = ipaddress;
            port = portp;


            if (ip == null) return false;

            Close();

            //启动
            enter = true;

            clientSocket =
                new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);

            IPAddress mIp = IPAddress.Parse(ip);
            IPEndPoint ip_end_point = new IPEndPoint(mIp, port);

            try
            {
                clientSocket.Connect(ip_end_point);
            }
            catch
            {
                Debug.Log("连接服务器失败");
                Close();
                if (onFail != null)
                    onFail();

                return false;
            }

            Debug.Log("连接服务器成功");

            Recievethread = new Thread(RecieveMessage);
            Recievethread.IsBackground = true;
            Recievethread.Start();

            return IsConnected();
        }

        public void Messages(string data)
        {
            // Debug.Log("服务器返回数据：" + data);

            string[] datas = data.Split('|');

            if (datas[0] == "0" && datas[1] == "0")
            {
                clientid = datas[2];


            }
            if (datas[0] == "0" && datas[1] == "1")
            {
                Debug.Log("服务器 in group :" + datas[2]);

            }

            //没有分配id,不接收数据
            if (clientid != null)
            {
                if (OnAction != null) OnAction(data);
                return;
            }





        }

        public void RecieveMessage()
        {
            while (enter)
            {
                try
                {
                    //服务器下发数据长度
                    int receiveLength = clientSocket.Receive(result);

                    if (receiveLength == 0) continue;
                    // ByteBuffer buffer = new ByteBuffer(result);

                    // int len = buffer.ReadShort();

                    // Debug.Log("服务器返回数据長：" + len);
                    string data = Encoding.GetEncoding("UTF-8").GetString(result);
                    Array.Clear(result, 0, result.Length);
                    // Debug.Log("服务器返回数据長：" + data);
                    // string data = buffer.ReadString();
                    Messages(data);
                }
                catch
                {
                    //连接可能中断
                    if (!IsConnected())
                    {
                        reconnent();
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 发送数据给服务器
        /// </summary>
        public void SendMessage(string data)
        {
            if (!IsConnected()) return;

            try
            {

                clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(data));
            }
            catch
            {
                Close();
            }
        }

        /// <summary>
        /// 信息数据转成数据集
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public static string[] toDatas(string datas)
        {
            return datas.Split('|');
        }

        /// <summary>
        /// 数据转成信息体
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string toMessages(string[] list)
        {
            return string.Join("|", list);
        }

        /// <summary>
        /// 数据转换，网络发送需要两部分数据，一是数据长度，二是主体数据
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static byte[] WriteMessage(byte[] message)
        {
            MemoryStream ms = null;
            using (ms = new MemoryStream())
            {
                ms.Position = 0;
                BinaryWriter writer = new BinaryWriter(ms);
                // ushort msglen = (ushort)message.Length;
                // writer.Write(msglen);
                writer.Write(message);
                writer.Flush();
                return ms.ToArray();
            }
        }
    }
}
